package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"fmt"
	"strings"
)

// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
	block, _ := pem.Decode(publicKey) //将密钥解析成公钥实例
	if block == nil {
		return nil, errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) //解析pem.Decode（）返回的Block指针实例
	if err != nil {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData) //RSA算法加密
}

// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey) //将密钥解析成私钥实例
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) //解析pem.Decode（）返回的Block指针实例
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext) //RSA算法解密
}

//私钥
var privateKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC6LKFg1wEBn2PWKShPOL2JbcQNWOp9zYq1Pumq/Y0moRWSmJNl
ZKS86KUYIwtyHlDC6Cqd3D6TfmqWm/S3sKkARvohf1+/jloznu31cKueAdrct14K
/TDqdSLbmzNe/xeTptkyQePSgnbZi1hIIusxvMumhtumvqEb0oF7iLbOjwIDAQAB
AoGAcLIJcexUIJ5SOdYqH2JyYRk/vvCe6U4dc79EhQv8gHCr9VREjPDSQ8P0A9ta
11aAfqs4+NvUSUYR0V9QUE0wzwB03KbreDBUWL0lZ69QPP6pCL7u92DGOE2Ht8+n
mzkgRc/1CqzG5d5qRcn9PQUBCUVvpbVY1t6trsFDATCffWECQQDmmC8RS+gm1yIP
O1V6kCaeV6A5M0U4f8i2UKQhCHXM6m/SAyVjwjWc+Ov7EQzrNoa9L5sqFJgrj7Fz
gOyBhum/AkEAzq+YnhMf2rV3eLlPsyaR80LdPuI0pzkrKyLLSFPrx2nWh0wCKCGp
C6raXS6/j+s/DghfChww43uSgM4RIYYvMQJAR/GNJclX+d4/Cx+I8L9OvTI7k/0S
CKmdlnwcaQ35quAt2QkQPkqWbY4gGenc7PnLGfVjZMKeI2EmjRHZOCQ+gwJAVyDI
2mI/fGghHAAqa+AniH+4Wqjq/09nNkDtpujRrPed2t0cz6QY6fU1JjDtyhKmOxkm
T1HA/jR6dtfnetVhEQJBAN3ZA3pHM/yJOOBiBSwl8HFjbUJMLvnhMf2TwG4Vc96n
mtTEgh/5Kdg/WQVP5FPuOwHgBhAMezkNrwHRUnzUjSw=
-----END RSA PRIVATE KEY-----`)

//公钥
var publicKey = []byte(`-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCreBTw4mYeQDDmC7crYLzQwoBv
TCCNSGDFPNBza/zHviK8yCot1atiFHy+4nHcUMF6Dfv3enzHhW+79pa6SrGeg9Dg
Mx+0kDiRXkJhzI8n9j2jAS0FEEy/wA3cYbbte7ecBlcXL8yzEdVpUf7uQwCQ67Fb
ShhdU7G3miVSeYb2jQIDAQAB
-----END PUBLIC KEY-----`)

func main() {

	data, err := RsaEncrypt([]byte("polaris@studygolang.com")) //RSA加密
	if err != nil {
		panic(err)
	}
	fmt.Println("RSA加密", string(data))
	data = []byte("DjonnnKJOx76E9Hsru2WWBdbxnZS8ThEIAuHZBkm1ESdhIhrNG4C5R9CpP0beJlSGN+NtXJ/pfH2vvxC2/KgXHo1M+g2ieJDtWbgjrslycBjv1Ow/e7i20T/aZha2R+nMETKnQp7dMsPKWodRpffiWg+f8nnm33DUQjP4fUpiIA=")
	data, _ = base64.StdEncoding.DecodeString(strings.Replace(string(data), "%2B", "+", -1))
	fmt.Println("test", data)
	origData, err := RsaDecrypt(data) //RSA解密
	if err != nil {
		panic(err)
	}
	fmt.Println("RSA解密", string(origData))
}
